/**
 *  认证模块
 *  writen by Yanjun tang(312976625@qq.com)
 */

const app = getApp();

const Logger = app.modules['Logger'];
const Storage = app.modules['Storage'];
const Request = app.modules['Requesst'];
//认证信息的缓存KEY
const CACHE_KEY = 'auth_info';

//token 或者 sessionid
// var _identifier = ''; 

//认证后的用户信息
// var _authed_user = null;

var _auth_info = {
    identifier:'',
    user:null
};

module.exports = {

    /**
     * 支持在应用启动的时候从storage上恢复数据
     */
    boot:function(app){
        Logger.debug('[bootting] Auth');
        var auth_info = Storage.get(CACHE_KEY,false);
        if (auth_info){
            //恢复用户信息和回话信息
            _auth_info = auth_info;
        }
    },

    //返回当前的用户
    user:function(){
        return _auth_info.user;
    },

    identifier:function(){
        return _auth_info.identifier;
    },
    //登录
    attempt:function(data,callback1,callback2){
        const Request = app.modules['Request'];
        Request.post('/login.php', data).then(function (res) {
            if (res.data.errcode == 0) {
                var contents = res.data.contents;
                _auth_info.identifier = contents.sessionid;
                _auth_info.user = contents.user;
                Storage.set(CACHE_KEY, _auth_info);
                if (callback1 != undefined) {
                    callback1(_auth_info);
                }
            } else {
                Logger.error(res);
                if (callback2 != undefined) {
                    callback2(res);
                }
            }

        }, function (res) {
            console.log(res);
            if (callback2 != undefined) {
                Logger.error(res);
                callback2(res);
            }
        });
    },

    //退出登录
    logout:function(){
        _identifier = '';
        _authed_user = null;
        Storage.remove(CACHE_KEY);
    }
}